package com.zheng.shop.rpc.service.impl;

import com.zheng.common.annotation.BaseService;
import com.zheng.common.base.BaseServiceImpl;
import com.zheng.shop.common.exception.ShopException;
import com.zheng.shop.dao.mapper.ShopSkuAttributeMapper;
import com.zheng.shop.dao.mapper.ShopSkuMapper;
import com.zheng.shop.dao.model.ShopSkuAttribute;
import com.zheng.shop.rpc.api.ShopSkuAttributeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zheng.common.annotation.BaseService;
import com.zheng.common.base.BaseServiceImpl;
import com.zheng.shop.dao.mapper.ShopSkuAttributeMapper;
import com.zheng.shop.dao.model.ShopSku;
import com.zheng.shop.dao.model.ShopSkuAttribute;
import com.zheng.shop.dao.model.ShopSkuAttributeSku;
import com.zheng.shop.rpc.api.ShopSkuAttributeService;
import com.zheng.shop.rpc.api.ShopSkuAttributeSkuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author likun
 * @since 2017-12-29
 */
@Service
@Transactional(rollbackFor = ShopException.class)
@BaseService
public class ShopSkuAttributeServiceImpl extends BaseServiceImpl<ShopSkuAttributeMapper, ShopSkuAttribute> implements ShopSkuAttributeService {

    @Autowired
    private ShopSkuAttributeMapper shopSkuAttributeMapper;
    @Autowired
    private ShopSkuAttributeSkuService skuAttributeSkuService;

    //添加sku属性，并返回添加的集合
    public List<ShopSkuAttribute> createSkuAttribute(JSONArray attributeArray) throws Exception {
        List<ShopSkuAttribute> skuAttributeList = new ArrayList<>();
        for (int i = 0; i < attributeArray.size(); i++) {
            JSONObject json = attributeArray.getJSONObject(i);
            JSONArray values = json.getJSONArray("values");
            for (int j = 0; j < values.size(); j++) {
                ShopSkuAttribute skuAttribute = json.toJavaObject(ShopSkuAttribute.class);
                skuAttribute.setId(null);
                JSONObject value = values.getJSONObject(j);
                skuAttribute.setAttributeValue(value.getString("value"));
                if (json.getBoolean("hasImage")) {
                    skuAttribute.setImage(value.getString("images"));
                }
                if (!insert(skuAttribute)) {
                    throw new Exception("添加sku属性失败！");
                }
                skuAttributeList.add(skuAttribute);
            }
        }
        return skuAttributeList;
    }

    @Override
    public List<ShopSkuAttribute> selectSkuAttributeList(Integer skuId) {
        return shopSkuAttributeMapper.selectSkuAttributeList(skuId);
    }
}
